package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationReportService;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;

@Api(description = "微信端撤回，删除，共享")
@RestController
@RequestMapping("/stationReportController")
public class StationReportController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StationReportService stationReportService;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private UserLogRepository userLogRepository;

    @ApiOperation("删除/撤回报告")
    @RequestMapping(value = "withdraw_deleteReport", method = RequestMethod.POST)
    public JsonResponse withdraw_deleteReport(Principal principal,
                                              @ApiParam("报告类型") @RequestParam(value = "reportType") String reportType,
                                              @ApiParam("操作类型：delete,withdraw") @RequestParam(value = "operation") String operation,
                                              @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId) {
        String stationName = "";
        String stationNum = "";
        if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
            AuditColorReport auditColorReport = auditColorReportRepository.selectReport(reportId, 175L);
            AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(reportId, 181L);
            if (null != auditColorReport) {
                stationName = auditColorReport.getAnswerOther();
            }
            if (null != auditColorReportNum) {
                stationNum = auditColorReportNum.getAnswerOther();
            }
        } else if (reportType.equals(Constants.SERVICE_REPORT)) {
            StationReport stationReport = stationReportRepository.findOne(reportId);
            if (null != stationReport && null != stationReport.getStation()) {
                stationName = stationReport.getStation().getName();
                stationNum = stationReport.getStation().getStationNum();
            }
        }


        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        JsonResponse jsonResponse = stationReportService.withdraw_deleteReport(clientUser, reportType, operation, reportId);
        if (jsonResponse.isSuccess()) {
            //     删除报告===================================
            try {
                String operate = "";
                if (Constants.WITHDRAW_REPORT.equals(operation)) {
                    operate = LogConstants.operate_type_withdraw;
                } else if (Constants.DELETE_REPORT.equals(operation)) {
                    operate = LogConstants.operate_type_delete;
                }
                String businessType = "";
                if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
                    businessType = LogConstants.business_type_customer;
                } else if (reportType.equals(Constants.SERVICE_REPORT)) {
                    businessType = LogConstants.business_type_regular_report;
                } else {
                    businessType = LogConstants.business_type_customer;
                }
                UserLog userLog = userLogService.addUserLog(clientUser, null, reportId, reportType, operate, businessType, null, null);
                userLog.setStationName(stationName);
                userLog.setStationNo(stationNum);
                userLogRepository.save(userLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonResponse;
    }

    @ApiOperation("撤回提示语")
    @RequestMapping(value = "checkWithdraw_deleteReport", method = RequestMethod.POST)
    public JsonResponse checkWithdraw_deleteReport(Principal principal,
                                                   @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                                   String reportType) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        if (reportType.equals(Constants.TECHCOLOR_REPORT)) {
            AuditReport auditReport = auditReportRepository.findOne(reportId);
            if (auditReport == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
            } else {
                if (auditReport.getStation() != null) {
                    QStationReport qStationReport = QStationReport.stationReport;
                    BooleanBuilder builder = new BooleanBuilder();
                    builder.and(qStationReport.deleted.eq(false));
                    builder.and(qStationReport.enabled.eq(true));
                    builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
                    builder.and(qStationReport.station.id.eq(auditReport.getStation().getId()));
                    StationReport stationReport = stationReportRepository.findOne(builder);
                    if (stationReport != null) {
                        stationReport.setAuditing(Constants.AUDIT_TRUE);
                        stationReportRepository.save(stationReport);
                    }
                }
                return JsonResponse.successResponse();
            }
        } else if (reportType.equals(Constants.SERVICE_REPORT)) {
            StationReport stationReport = stationReportRepository.findOne(reportId);
            if (stationReport == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
            } else {
                QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
                BooleanBuilder booleanBuilder = new BooleanBuilder();
                booleanBuilder.and(qCustomerRegularReport.deleted.eq(false));
                booleanBuilder.and(qCustomerRegularReport.enabled.eq(true));
                booleanBuilder.and(qCustomerRegularReport.regularReport.id.eq(stationReport.getId()));
                CustomerRegularReport customerRegularReport = customerRegularReportRepository.findOne(booleanBuilder);
                if (customerRegularReport != null && customerRegularReport.getCustomerReport() != null) {
                    return JsonResponse.successResponseWithData("客户已填写满意度报告，此操作会使满意度分数失效，是否继续撤回？");
                } else {
                    return JsonResponse.successResponse();
                }
            }
        }
        return JsonResponse.successResponse();
    }

    @ApiOperation("检查报告是否可以编辑--主要针对基础报告")
    @RequestMapping(value = "checkReport", method = RequestMethod.POST)
    public JsonResponse checkReport(Principal principal,
                                    @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        StationReport stationReport = stationReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }

        if (stationReport.getCategory().equals(Constants.TECHCOLOR_REPORT)) {
            if (stationReport.getAuditing().equals(Constants.AUDIT_APPLY)) {
                return JsonResponse.successResponseWithData("此报告有用户提交了审核,正在审核中,无法进行编辑");
            }
            if (stationReport.getStation() != null && stationReport.getStation().getId() != null) {
                Long stationid = stationReport.getStation().getId();
                QAuditReport qAuditReport = QAuditReport.auditReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qAuditReport.deleted.eq(false));
                builder.and(qAuditReport.enabled.eq(true));
                builder.and(qAuditReport.station.id.eq(stationid));
                builder.and(qAuditReport.category.eq(Constants.TECHCOLOR_REPORT));
                builder.and(qAuditReport.user.id.eq(clientUser.getId()));
                List<AuditReport> auditReport = (List<AuditReport>) auditReportRepository.findAll(builder);
                if (auditReport != null && auditReport.size() != 0) {
                    return JsonResponse.successResponseWithData("您曾经对此客户做过修改，请在我的报告里进行操作");
                }
            }
        }
        return JsonResponse.successResponse();
    }


}
